package com.zhima.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zhima.dto.AuthParamsDTO;
import com.zhima.dto.CreateOjUserDTO;
import com.zhima.dto.UserDTOExtension;
import com.zhima.exception.ZhimaOjException;
import com.zhima.feignclient.CheckCodeFeignClient;
import com.zhima.feignclient.UserFeignClient;
import com.zhima.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class EmailAuthServiceImpl implements AuthService {
    @Autowired
    private CheckCodeFeignClient checkCodeFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDTOExtension auth(AuthParamsDTO authParamsDTO) {
        String message = checkCodeFeignClient.verifyEmailCheckCode(authParamsDTO.getEmail(), authParamsDTO.getCheckCode());
        // 返回不为空，则说明出现了异常
        if (StrUtil.isNotEmpty(message)) {
            throw new ZhimaOjException(message);
        }
        // 如果数据库不存在此邮箱的用户，默认注册
        UserDTOExtension userDTOExtension = userFeignClient.authInfoByEmail(authParamsDTO.getEmail());
        if (userDTOExtension != null) {
            return userDTOExtension;
        }
        CreateOjUserDTO ojUser = new CreateOjUserDTO();
        ojUser.setEmail(authParamsDTO.getEmail());
        return createPlainUser(ojUser, passwordEncoder, userFeignClient);
    }
}
